package com.billing.web.controller.message;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.billing.config.ServiceConfig;
import com.billing.model.entity.Articletype;
import com.billing.model.entity.Comment;
import com.billing.model.entity.CommentAppBean;
import com.billing.model.entity.Consultation;
import com.billing.model.entity.ConsultingAppsingle;
import com.billing.model.entity.ContentType;
import com.billing.model.entity.Message;
import com.billing.model.entity.MessageAppsingle;
import com.billing.model.entity.TMaindata;
import com.billing.model.entity.TUser;
import com.billing.service.ArticletypeService;
import com.billing.service.ConsultationService;
import com.billing.service.ContentTypeService;
import com.billing.service.MaindataService;
import com.billing.service.ManagerPermissionsService;
import com.billing.service.MessageService;
import com.billing.service.UserService;

/**
 * @author Administrator
 *
 */
@RequestMapping(value="/message")
@Controller
public class messageController {
	
	@Resource
	private ContentTypeService contenttypeservice;
	@Resource
	private MessageService messageservice;
	@Resource
	private UserService userService;
	@Resource
	private ConsultationService consultationservice;
	@Resource
	private ArticletypeService articletypeservice;
	@Resource
	private MaindataService maindataService;
	@Resource
	private ManagerPermissionsService managerService;
	
	/**
	 * @param request
	 * @param model
	 * @return
	 * 消息列表
	 * @throws Exception 
	 */
	@RequestMapping(value="/mainpage",method=RequestMethod.GET)
	public String mainpage(HttpServletRequest request, Model model) throws Exception{
		String title = request.getParameter("titletext");
		String cont = request.getParameter("cont");
		String status = request.getParameter("status") == null ? "" : request.getParameter("status");
		
		String startDate = request.getParameter("startDate") == null ? "" : request.getParameter("startDate");//开始时间
		String endDate = request.getParameter("endDate") == null ? "" : request.getParameter("endDate");//结束时间
		
		int pageSize = 10;
		
		try {
			if (title!=null&&title.length() > 0) {
				title = URLDecoder.decode(URLDecoder.decode(title, "UTF-8"),"UTF-8");
			}
		} catch (UnsupportedEncodingException e) {
		}
		List<ContentType> contentlist = contenttypeservice.getContentTypelist();
		request.setAttribute("contentlist", contentlist);
		request.setAttribute("title", title);
		request.setAttribute("cont", cont);
		request.setAttribute("startDate", startDate);
		request.setAttribute("endDate", endDate);
		request.setAttribute("status", status);
		
		// 获取当前页数
		int currentPage = 1;
		try {
			currentPage = new Integer(request.getParameter("currentPage"));
		} catch (Exception e) {
		}
		currentPage = currentPage <= 0 ? 1 : currentPage;
		int organizationid=(int) request.getSession().getAttribute("organizationid");
		
		int totalNum = messageservice.selectmessgeNum(title, cont, organizationid);
		int totalPage = totalNum / pageSize;
		if (totalNum % pageSize != 0) {
			totalPage++;	
		}
		totalPage = totalPage <= 0 ? 1 : totalPage;
		currentPage = currentPage > totalPage ? totalPage : currentPage;
		List<Message> messlist = messageservice.selectmessgeList(title, cont, status, startDate, endDate, organizationid, (currentPage - 1) * pageSize, pageSize);
		
		request.setAttribute("totalNum", totalNum);
		request.setAttribute("list", messlist);
		request.setAttribute("currentPage", currentPage);
        request.setAttribute("totalNum", totalNum);
        request.setAttribute("totalPage", totalPage);
		return "message/message";
	}
	
	
	/**
	 * @param request
	 * @param model
	 * @return
	 * 消息审核
	 */
	@RequestMapping(value="/examinepage",method=RequestMethod.GET)
	public String examinepage(HttpServletRequest request, Model model){
		Integer userid = (Integer) request.getSession().getAttribute("managerid");
		List<Message> examine = messageservice.selectexamine();
		request.setAttribute("list", examine);
		boolean mp = managerService.selectPermissionsByCode(userid,"examine");
		if (mp) {
			request.setAttribute("Code","examine");
		}
		return "message/examine";
	}
	
	/**
	 * @param request
	 * @param model
	 * @return
	 * 回收站
	 */
	@RequestMapping(value="/recyclepage",method=RequestMethod.GET)
	public String recyclepage(HttpServletRequest request, Model model){
		
		List<Message> examine = messageservice.selrecyclebin();
		request.setAttribute("list", examine);
		return "message/recycle";
	}
	
	/**
	 * 新增页面
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "addpage",method = RequestMethod.GET)
	public String addpage(HttpServletRequest request,Model model){
		
		List<ContentType> contentlist = contenttypeservice.getContentTypelist();
		request.setAttribute("contentlist", contentlist);
		return "message/addDisplay";
	}
	
	/**
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "save",method = RequestMethod.POST)
	public String save(HttpServletRequest request,Model model){
		Integer userid = (Integer) request.getSession().getAttribute("managerid");//获取当前登录人员的ID
		int organizationId=(int) request.getSession().getAttribute("organizationid");
		Date d = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		try {
			String title = request.getParameter("title");
			String author = request.getParameter("author");
			String contenttypeid = request.getParameter("contenttypeid");
			if("".equals(contenttypeid)){
				contenttypeid = "9";
			}
			String source = request.getParameter("source");
			String introduction = request.getParameter("introduction");
			
			String linkaddress = request.getParameter("linkaddress");
			String starttime = sdf.format(d);//request.getParameter("starttime");
			String endtime = sdf.format(d);//request.getParameter("endtime");
			String summary = request.getParameter("summary");
			//String createtime = sdf.format(d);
			
			
			long date = new Date().getTime();  
			System.out.println(date);
			
			Message news = new Message();
			news.setContenttypeid(contenttypeid);//9:其他
			news.setTitle(title);
			news.setAuthor(author);
			news.setSummary(summary);
			news.setSource(source);
			news.setIntroduction(introduction);
			news.setLinkaddress(linkaddress);
			news.setAddeddate(date);//添加时间--当前时间戳
			news.setReleasestate(1);
			news.setStatus(2);
			news.setUserid(userid);
			news.setOrganizationId(organizationId);
			news.setStarttime(starttime);
			news.setEndtime(endtime);
			news.setExistencestatus(1);
			news.setReadornot(1);
			
			messageservice.insertMessage(news);
			
			request.setAttribute("msg", "新增成功!");
			return "message/addDisplay";
			
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("msg", "新增失败!");
			return "message/addDisplay";
		}
		
	}
	
	/**
	 * 修改页面
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "updatedapage",method = RequestMethod.GET)
	public String updatedapage(HttpServletRequest request,Model model){
		Integer userid = (Integer) request.getSession().getAttribute("managerid");//获取当前登录人员的ID
		List<ContentType> contentlist = contenttypeservice.getContentTypelist();
		request.setAttribute("contentlist", contentlist);
		
		String type=request.getParameter("type");
		
		String id = request.getParameter("id");
		Message message = messageservice.selectmessgebyId(id);
		String uid = message.getUser().getId().toString();
		String uname="";
		if("2".equals(type)){
			String auid = message.getAuditor() == null ? "" : message.getAuditor();
			if(auid != ""){
				TUser user = userService.getTUserById(auid);
				uname = user.getName();
			}
		}
		int pageSize = 10;
		// 获取当前页数
		int currentPage = 1;
		try {
			currentPage = new Integer(request.getParameter("currentPage"));
		} catch (Exception e) {
		}
		currentPage = currentPage <= 0 ? 1 : currentPage;
		int organizationid=(int) request.getSession().getAttribute("organizationid");
		int totalNum = messageservice.selectmessgeNum("", "", organizationid);
		int totalPage = totalNum / pageSize;
		if (totalNum % pageSize != 0) {
			totalPage++;	
		}
		totalPage = totalPage <= 0 ? 1 : totalPage;
		currentPage = currentPage > totalPage ? totalPage : currentPage;
		Long startDate = null;
		Long endDate = null;
		List<Message> messlist = messageservice.selectmessgeList("", "", "","", "", organizationid,(currentPage - 1) * pageSize, pageSize);
		request.setAttribute("list", messlist);
		
		request.setAttribute("meslist", message);
		request.setAttribute("type", type);
		request.setAttribute("id", id);
		request.setAttribute("uid", uid);
		request.setAttribute("uname", uname);
		
		return "message/updatemessage";
	}
	
	/**
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "update",method = RequestMethod.POST)
	public String update(HttpServletRequest request,Model model){
		String type = request.getParameter("type");
		Integer userid = (Integer) request.getSession().getAttribute("managerid");//获取当前登录人员的ID
		int organizationId=(int) request.getSession().getAttribute("organizationid");
		Date d = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		try {
			String title = request.getParameter("title");
			String author = request.getParameter("author");
			String contenttypeid = request.getParameter("contenttypeid");
			String source = request.getParameter("source");
			String introduction = request.getParameter("introduction");
			String id = request.getParameter("id");
			String linkaddress = request.getParameter("linkaddress");
			String starttime = sdf.format(d);//request.getParameter("starttime");
			String endtime = sdf.format(d);//request.getParameter("endtime");
			String summary = request.getParameter("summary");
			//String addeddate = request.getParameter("addeddate");
			
			Message xmessage = messageservice.selectmessgebyId(id);
			int uid = xmessage.getUser().getId();
			long addeddate = xmessage.getAddeddate();
			
			Message message = new Message();
			message.setContenttypeid(contenttypeid);
			message.setTitle(title);
			message.setAuthor(author);
			message.setSummary(summary);
			message.setSource(source);
			message.setIntroduction(introduction);
			message.setLinkaddress(linkaddress);
			message.setAddeddate(addeddate);
			message.setReleasestate(1);
			message.setStatus(2);
			message.setUserid(uid);
			message.setOrganizationId(organizationId);
			message.setStarttime(starttime);
			message.setEndtime(endtime);
			message.setId(id);
			message.setExistencestatus(1);
			
			messageservice.updateMessage(message);
			request.setAttribute("type", type);
			request.setAttribute("uid", "");
			request.setAttribute("uname", "");
			request.setAttribute("msg", "修改成功!");
			return "message/updatemessage";
			
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("type", type);
			request.setAttribute("uid", "");
			request.setAttribute("uname", "");
			request.setAttribute("msg", "修改失败!");
			return "message/updatemessage";
		}
	}
	
	/**
	 * 
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception 
	 * 提交审核数据
	 */
	@RequestMapping(value="/examineMessage",method=RequestMethod.POST)
	public String examineMessage(HttpServletRequest request, Model model) throws Exception{
		String id = request.getParameter("id");
		if(id!=null&&id!=""){
			messageservice.examineMessage(id);
		}
		return mainpage(request, model);
	}
	
	
	/**
	 * 审核页面
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "Auditpage",method = RequestMethod.GET)
	public String Auditpage(HttpServletRequest request,Model model){
		Integer userid = (Integer) request.getSession().getAttribute("managerid");//获取当前登录人员的ID
		List<ContentType> contentlist = contenttypeservice.getContentTypelist();
		request.setAttribute("contentlist", contentlist);
		
		
		String id = request.getParameter("id");
		Message message = messageservice.selectmessgebyId(id);
		String uid = message.getUser().getId().toString();
		
		int pageSize = 10;
		// 获取当前页数
		int currentPage = 1;
		try {
			currentPage = new Integer(request.getParameter("currentPage"));
		} catch (Exception e) {
		}
		currentPage = currentPage <= 0 ? 1 : currentPage;
		int organizationid=(int) request.getSession().getAttribute("organizationid");
		int totalNum = messageservice.selectmessgeNum("", "", organizationid);
		int totalPage = totalNum / pageSize;
		if (totalNum % pageSize != 0) {
			totalPage++;	
		}
		totalPage = totalPage <= 0 ? 1 : totalPage;
		currentPage = currentPage > totalPage ? totalPage : currentPage;
		Long startDate = null;
		Long endDate = null;
		List<Message> messlist = messageservice.selectmessgeList("", "", "","", "", organizationid,(currentPage - 1) * pageSize, pageSize);
		request.setAttribute("list", messlist);
		
		request.setAttribute("meslist", message);
		request.setAttribute("id", id);
		request.setAttribute("uid", uid);
		
		return "message/Auditpage";
	}
	
	
	/**
	 * 
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception 
	 * 审核数据
	 */
	@RequestMapping(value="/AuditdataMess",method=RequestMethod.POST)
	public String AuditdataMess(HttpServletRequest request, Model model) throws Exception{
		
		String userid = request.getSession().getAttribute("managerid").toString();//获取当前登录人员的ID
		int organizationId=(int) request.getSession().getAttribute("organizationid");
		Date d = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat asdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			String title = request.getParameter("title");
			String author = request.getParameter("author");
			//String contenttypeid = request.getParameter("hcontenttypeid");
			String source = request.getParameter("source");
			String introduction = request.getParameter("introduction");
			
			String linkaddress = request.getParameter("linkaddress");
			String starttime = sdf.format(d);//request.getParameter("starttime");
			String endtime = sdf.format(d);//request.getParameter("endtime");
			String summary = request.getParameter("summary");
			//String createtime = sdf.format(d);
			String audittime = asdf.format(d);
			String auditopinion = request.getParameter("auditopinion");//上级审核意见
			
			String id = request.getParameter("id");
			Message xmessage = messageservice.selectmessgebyId(id);
			int uid = xmessage.getUser().getId();
			long createtime = xmessage.getAddeddate();
			String contenttypeid = xmessage.getContenttypeid();
			
			Message news = new Message();
			news.setId(id);
			news.setContenttypeid(contenttypeid);
			news.setTitle(title);
			news.setAuthor(author);
			news.setSummary(summary);
			news.setSource(source);
			news.setIntroduction(introduction);
			news.setLinkaddress(linkaddress);
			news.setAddeddate(createtime);
			news.setReleasestate(1);
			news.setStatus(1);
			news.setUserid(uid);
			news.setOrganizationId(organizationId);
			news.setStarttime(starttime);
			news.setEndtime(endtime);
			
			news.setExistencestatus(1);//状态 1:正常 2:删除
			news.setAuditor(userid);//审核人(用户ID)
			news.setAudittime(audittime);//审核时间
			news.setAuditopinion(auditopinion);//上级审核意见
			
			
			request.setAttribute("uid", uid);
			messageservice.AuditData(news);
			
			request.setAttribute("msg", "审核成功!");
			return "message/Auditpage";
			
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("msg", "审核失败!");
			return "message/Auditpage";
		}
	}
	
	/**
	 * 
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception 
	 * 提交回收站
	 */
	@RequestMapping(value="/modifyStateMess",method=RequestMethod.POST)
	public String modifyStateMess(HttpServletRequest request, Model model) throws Exception{
		String id = request.getParameter("id");
		if(id!=null&&id!=""){
			messageservice.modifyState(id);
		}
		return mainpage(request, model);
	}
	
	/**
	 * @param request
	 * @param model
	 * @return
	 * 回收站消息
	 */
	@RequestMapping(value="/recyclebinpage",method=RequestMethod.GET)
	public String recyclebinpage(HttpServletRequest request, Model model){
		
		List<Message> examine = messageservice.selrecyclebin();
		request.setAttribute("list", examine);
		
		return "message/recycle";
	}
	
	/**
	 * 
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception 
	 * 回收站退回数据
	 */
	@RequestMapping(value="/returnMess",method=RequestMethod.POST)
	public String returnMess(HttpServletRequest request, Model model) throws Exception{
		String id = request.getParameter("id");
		if(id!=null&&id!=""){
			messageservice.ReturnMessage(id);
		}
		return mainpage(request, model);
	}
	
	/**
	 * 
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception 
	 * 删除数据
	 */
	@RequestMapping(value="/ddeleteMess",method=RequestMethod.POST)
	public String ddeleteMess(HttpServletRequest request, Model model) throws Exception{
		int id = Integer.parseInt(request.getParameter("id"));
		if(id > 0){
			messageservice.deleteMessageByid(id);
		}
		return mainpage(request, model);
	}
	
	/**
	 * @param request
	 * @param model
	 * @return
	 * 咨询入口
	 */
	@RequestMapping(value="/consultationpage",method=RequestMethod.GET)
	public String consultationpage(HttpServletRequest request, Model model){
		String consultingtitle = request.getParameter("hconsultingtitle");
		String art = request.getParameter("art");
		
		int pageSize = 10;
		
		try {
			if (consultingtitle!=null&&consultingtitle.length() > 0) {
				consultingtitle = URLDecoder.decode(URLDecoder.decode(consultingtitle, "UTF-8"),"UTF-8");
			}
		} catch (UnsupportedEncodingException e) {
		}
		List<Articletype> articletypelist = articletypeservice.getArticletypelist();
		request.setAttribute("articletypelist", articletypelist);
		request.setAttribute("consultingtitle", consultingtitle);
		request.setAttribute("art", art);
		
		// 获取当前页数
		int currentPage = 1;
		try {
			currentPage = new Integer(request.getParameter("currentPage"));
		} catch (Exception e) {
		}
		currentPage = currentPage <= 0 ? 1 : currentPage;
		int organizationid=(int) request.getSession().getAttribute("organizationid");
		
		int totalNum = consultationservice.selectConsuNum(consultingtitle, art, organizationid);
		int totalPage = totalNum / pageSize;
		if (totalNum % pageSize != 0) {
			totalPage++;	
		}
		totalPage = totalPage <= 0 ? 1 : totalPage;
		currentPage = currentPage > totalPage ? totalPage : currentPage;
		List<Consultation> conslist = consultationservice.getConsultationlist(consultingtitle, art, organizationid, (currentPage - 1) * pageSize, pageSize);
		
		request.setAttribute("list", conslist);
		request.setAttribute("currentPage", currentPage);
        request.setAttribute("totalNum", totalNum);
        request.setAttribute("totalPage", totalPage);
		
		return "message/Consultation";
	}
	
	/**
	 * 咨询修改/查看页面
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "conseditlookpage",method = RequestMethod.GET)
	public String conseditlookpage(HttpServletRequest request,Model model){
		Integer userid = (Integer) request.getSession().getAttribute("managerid");//获取当前登录人员的ID
		List<Articletype> articletypelist = articletypeservice.getArticletypelist();//下拉框
		request.setAttribute("articletypelist", articletypelist);
		
		String type=request.getParameter("type");//1:修改 2：查看
		String id = request.getParameter("id");
		
		Consultation consultation = consultationservice.selectConsubyId(id);
		
		request.setAttribute("conlist", consultation);
		request.setAttribute("type", type);
		request.setAttribute("id", id);
		
		return "message/ConsultationLook";
	}
	
	/**
	 * 显示图片页面
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/imgmain",method=RequestMethod.GET)
	public String imgmain(HttpServletRequest request, Model model){
		String path=request.getParameter("path");
		request.setAttribute("path",path);
		return "message/imgmain";
	}
	
	@RequestMapping("lookimage")  
    public void lookimage(HttpServletRequest request,HttpServletResponse response) throws Exception{ 
        //图片
    	String path=request.getParameter("path");
        String filepath=ServiceConfig.fileUploadPath +"/"+path.split("upload/")[1];
        File filePic = new File(filepath);
        if(filePic.exists()){
           FileInputStream is = new FileInputStream(filePic);
           int i = is.available(); // 得到文件大小  
           byte data[] = new byte[i];  
           is.read(data); // 读数据  
           is.close();  
           response.setContentType("image/*"); // 设置返回的文件类型  
           OutputStream toClient = response.getOutputStream(); // 得到向客户端输出二进制数据的对象  
           toClient.write(data); // 输出数据  
           toClient.close();  
        }
    } 
	
	/**
	 * 咨询修改方法
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "conseditlookupdate",method = RequestMethod.POST)
	public String conseditlookupdate(HttpServletRequest request,Model model){
		String type = request.getParameter("type");
		//Integer userid = (Integer) request.getSession().getAttribute("managerid");//获取当前登录人员的ID
		int organizationId=(int) request.getSession().getAttribute("organizationid");
		Date d = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		try {
			String consultingtitle = request.getParameter("consultingtitle");
			String outline = request.getParameter("outline");
			String writer = request.getParameter("writer");
			String articletypeid = request.getParameter("articletypeid");
			String belonging = request.getParameter("belonging");
			String sourceaddress = request.getParameter("sourceaddress");
			String path = request.getParameter("path");
			String article = request.getParameter("harticle");//内容
			
			String id = request.getParameter("id");
			Consultation consultation = consultationservice.selectConsubyId(id);
			Integer userid = consultation.getUserid();
			long addtime = consultation.getAddtime();
			
			Consultation cons = new Consultation();
			cons.setConsultingtitle(consultingtitle);
			cons.setOutline(outline);
			cons.setWriter(writer);
			cons.setArticletypeid(articletypeid);
			cons.setBelonging(belonging);
			cons.setSourceaddress(sourceaddress);
			cons.setPath(path);
			cons.setArticle(article);
			cons.setOrganizationId(organizationId);
			cons.setUserid(userid);
			cons.setAddtime(addtime);
			cons.setId(id);
			
			consultationservice.updateCons(cons);
			request.setAttribute("type", "");
			request.setAttribute("msg", "修改成功!");
			return "message/ConsultationLook";
			
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("type", "");
			request.setAttribute("msg", "修改失败!");
			return "message/ConsultationLook";
		}
		
	}
	
	/**
	 * 咨询修新增页面
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "conseditaddpage",method = RequestMethod.GET)
	public String conseditaddpage(HttpServletRequest request,Model model){
		List<Articletype> articletypelist = articletypeservice.getArticletypelist();//下拉框
		request.setAttribute("articletypelist", articletypelist);
		return "message/ConsultationAdd";
	}
	
	/**
	 * 咨询修新增方法
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "conseditadd",method = RequestMethod.POST)
	public String conseditadd(HttpServletRequest request,Model model){
		Integer userid = (Integer) request.getSession().getAttribute("managerid");//获取当前登录人员的ID
		int organizationId=(int) request.getSession().getAttribute("organizationid");
		Date d = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		try {
			String consultingtitle = request.getParameter("consultingtitle");
			String outline = request.getParameter("outline");
			String writer = request.getParameter("writer");
			String articletypeid = request.getParameter("articletypeid");//咨询类型id
			if("".equals(articletypeid)){
				articletypeid = "1";
			}
			String belonging = request.getParameter("belonging");
			String sourceaddress = request.getParameter("sourceaddress");
			String conspath = request.getParameter("path");
			String article = request.getParameter("harticle");//内容
			
			long date = new Date().getTime(); //添加时间--时间戳 
			System.out.println(date);
			
			Consultation cons = new Consultation();
			cons.setConsultingtitle(consultingtitle);
			cons.setOutline(outline);
			cons.setWriter(writer);
			cons.setArticletypeid(articletypeid);
			cons.setBelonging(belonging);
			cons.setSourceaddress(sourceaddress);
			cons.setPath(conspath);
			cons.setArticle(article);
			cons.setOrganizationId(organizationId);
			cons.setUserid(userid);
			cons.setAddtime(date);
			consultationservice.insertCons(cons);
			
		    
			Consultation consp = null;
	        
	        // 将当前上下文初始化给 CommonsMutipartResolver （多部分解析器）
		    CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
		    // 检查form中是否有enctype="multipart/form-data"
		    if (multipartResolver.isMultipart(request)) {
		    	// 将request变成多部分request
			    MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			    // 获取multiRequest 中所有的文件名
			    Iterator<String> iter = multiRequest.getFileNames();
			    while (iter.hasNext()) {
			    	// 一次遍历所有文件
			    	MultipartFile file = multiRequest.getFile(iter.next());
			    	if (!file.isEmpty()) {
			    		// 服务端保存文件的路径
				        String path = "";
				        // 数据库保存路径
				        String sqlpath = "";
				        String subpath = "/"+cons.getId()+"/"+UUID.randomUUID().toString().replace("-", "")+file.getOriginalFilename();
				        if("educationfile".equals(file.getName())){
					        path = ServiceConfig.fileUploadPath+"/conschart"+subpath; 
					  	    sqlpath = "upload"+"/conschart"+subpath;
					  	    consp = new Consultation();
					  	    consp.setPath(sqlpath);
					  	    consp.setId(cons.getId());
				        }
			    	}
			    }
	        }
	  	    consultationservice.insertpath(consp);
			
			request.setAttribute("msg", "新增成功!");
			return "message/ConsultationAdd";
			
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("msg", "新增失败!");
			return "message/ConsultationAdd";
		}
	}
	
	
	/**
	 * 
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception 
	 * 删除咨询数据
	 */
	@RequestMapping(value="/deleteCons",method=RequestMethod.POST)
	public String deleteCons(HttpServletRequest request, Model model) throws Exception{
		int id = Integer.parseInt(request.getParameter("id"));
		if(id > 0){
			consultationservice.deleteConsByid(id);
		}
		return mainpage(request, model);
	}
	/**************接口****************/
	
	/**
	 * APP查看全部详细消息
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/getMessagelistApp", method = RequestMethod.POST, produces = "text/json;charset=UTF-8")
	@ResponseBody
	public String getMessagelistApp(HttpServletRequest request, Model model) {
		Map<String, Object> map=new HashMap<String, Object>();
		JSONObject jsons =null;
		String msg=null;
		JSONObject jsonObject = null;
		String userid =null;//用户id
		String currentPageStr = null;//页码 
		String sign=null;//身份认证
		int examinesign = 0;
		int pageSize = 10;
		String json = request.getParameter("json");
		jsonObject = JSONObject.fromObject(json);
		try{
			userid =jsonObject.getString("userid");
			currentPageStr =jsonObject.getString("currentPage");
		}catch(Exception e){
			map.put("msg", "参数有误"+e.getMessage().replaceAll("",""));
			map.put("code", 9002);
			jsons = JSONObject.fromObject(map);
            return jsons.toString();
		}

		// 获取当前页数
		int currentPage = 1;
		try {
			if(currentPageStr!=null && currentPageStr!=""){
				currentPage = Integer.parseInt(currentPageStr);
			}
		} catch (Exception e) {
		}
		currentPage = currentPage <= 0 ? 1 : currentPage;
		
		
		try {
			Map<String, Object> message = messageservice.selMessageId(pageSize, currentPage);
			int messNum = ((List)message.get("list")).size(); //
			if(messNum > 0){
				message.put("pageSize", pageSize);
				message.put("currentPage", currentPage);
				message.put("messNum", messNum);//总消息数
				
				map.put("data", message);
				map.put("code", 1);
				jsons = JSONObject.fromObject(map);// 将java对象转换为json对象
				msg = jsons.toString();
			} else {
				message.put("pageSize", pageSize);
				message.put("currentPage", currentPage);
				message.put("messNum", messNum);//总消息数
				
				map.put("data", message);
				map.put("msg", "暂无消息");
				map.put("code", 1);
				jsons = JSONObject.fromObject(map);// 将java对象转换为json对象
				msg = jsons.toString();
			}
		} catch (Exception e) {
			e.printStackTrace();
			map.put("msg", "获取详细信息失败"+e.getMessage().replaceAll("",""));
			map.put("code", 2);
			jsons = JSONObject.fromObject(map);
		}
		return msg;
	}
	
	/**
	 * APP查看登录用户单个详细消息
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/getMessageSingleApp", method = RequestMethod.POST, produces = "text/json;charset=UTF-8")
	@ResponseBody
	public String getMessageSingleApp(HttpServletRequest request, Model model) {
		Map<String, Object> map=new HashMap<String, Object>();
		JSONObject jsons =null;
		String msg=null;
		JSONObject jsonObject = null;
		String userid =null;//用户id
		String id="";//消息id
		int readornot = 0;//消息状态(0：已读)
		String sign=null;//身份认证
		String json = request.getParameter("json");
		jsonObject = JSONObject.fromObject(json);
		try{
			userid =jsonObject.getString("userid");
			id =jsonObject.getString("id");
			readornot =jsonObject.getInt("readornot");
		}catch(Exception e){
			map.put("msg", "参数有误"+e.getMessage().replaceAll("",""));
			map.put("code", 9002);
			jsons = JSONObject.fromObject(map);
            return msg;
		}
		try {
			Message readmes = new Message();
			readmes.setId(id);
			readmes.setReadornot(readornot);
			messageservice.updatereadtype(readmes);
			
			Message message = messageservice.selMessagebyId(id);//根据登录查看单条详细
			MessageAppsingle messageapp=new MessageAppsingle();
			BeanUtils.copyProperties(messageapp, message);
			map.put("data", messageapp);
			map.put("code", 1);
			jsons = JSONObject.fromObject(map);// 将java对象转换为json对象
			msg = jsons.toString();
		} catch (Exception e) {
			e.printStackTrace();
			map.put("msg", "获取详细信息失败"+e.getMessage().replaceAll("",""));
			map.put("code", 2);
			jsons = JSONObject.fromObject(map);
			return msg;
		}
		return msg;
	}
	
	/**
	 * APP查看登录用户未读消息
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/getMessageUnreadApp", method = RequestMethod.POST, produces = "text/json;charset=UTF-8")
	@ResponseBody
	public String getMessageUnreadApp(HttpServletRequest request, Model model) {
		Map<String, Object> map=new HashMap<String, Object>();
		JSONObject jsons =null;
		String msg=null;
		JSONObject jsonObject = null;
		String userid =null;//用户id
		String currentPageStr = null;//页码 
		String sign=null;//身份认证
		int pageSize = 10;
		String json = request.getParameter("json");
		jsonObject = JSONObject.fromObject(json);
		try{
			userid =jsonObject.getString("userid");
			//currentPageStr =jsonObject.getString("currentPage");
		}catch(Exception e){
			map.put("msg", "参数有误"+e.getMessage().replaceAll("",""));
			map.put("code", 9002);
			jsons = JSONObject.fromObject(map);
            return jsons.toString();
		}

		// 获取当前页数
		int currentPage = 1;
		try {
			if(currentPageStr!=null && currentPageStr!=""){
				currentPage = Integer.parseInt(currentPageStr);
			}
		} catch (Exception e) {
		}
		currentPage = currentPage <= 0 ? 1 : currentPage;
		
		
		try {
			List<TMaindata> recent = maindataService.getRecentMaindata(userid);
			Map<String, Object> message = messageservice.selUnreadMessageId(userid, pageSize, currentPage);
			int UnreadNum = ((List)message.get("list")).size(); //

			Map<String,Object> data = new HashMap<>();
			if(!recent.isEmpty()) {
				data.put("approveTitle", recent.get(0).getTitle());
				data.put("approveTime", recent.get(0).getMidifytime());
			}
			data.put("total", UnreadNum);
			map.put("data", data);
			map.put("code", 1);
			jsons = JSONObject.fromObject(map);// 将java对象转换为json对象
			msg = jsons.toString();
		} catch (Exception e) {
			e.printStackTrace();
			map.put("msg", "获取详细信息失败"+e.getMessage().replaceAll("",""));
			map.put("code", 2);
			jsons = JSONObject.fromObject(map);
		}
		return msg;
	}
	
	/*****************/
	
	/**
	 * APP查看所有咨询
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/getConsultationlistApp", method = RequestMethod.POST, produces = "text/json;charset=UTF-8")
	@ResponseBody
	public String getConsultationlistApp(HttpServletRequest request, Model model) {
		Map<String, Object> map=new HashMap<String, Object>();
		JSONObject jsons =null;
		String msg=null;
		JSONObject jsonObject = null;
		String userid =null;//用户id
		String currentPageStr = null;//页码 
		int pageSize = 10;
		String json = request.getParameter("json");
		jsonObject = JSONObject.fromObject(json);
		try{
			userid =jsonObject.getString("userid");
			currentPageStr =jsonObject.getString("currentPage");
		}catch(Exception e){
			map.put("msg", "参数有误"+e.getMessage().replaceAll("",""));
			map.put("code", 9002);
			jsons = JSONObject.fromObject(map);
            return jsons.toString();
		}

		// 获取当前页数
		int currentPage = 1;
		try {
			if(currentPageStr!=null && currentPageStr!=""){
				currentPage = Integer.parseInt(currentPageStr);
			}
		} catch (Exception e) {
		}
		currentPage = currentPage <= 0 ? 1 : currentPage;
		
		try {
			Map<String, Object> cons = consultationservice.selConsultationId(pageSize, currentPage);
			int messNum = ((List)cons.get("list")).size(); //
			if(messNum > 0){
				cons.put("pageSize", pageSize);
				cons.put("currentPage", currentPage);
				cons.put("messNum", messNum);//总消息数
				
				map.put("data", cons);
				map.put("code", 1);
				jsons = JSONObject.fromObject(map);// 将java对象转换为json对象
				msg = jsons.toString();
			} else {
				cons.put("pageSize", pageSize);
				cons.put("currentPage", currentPage);
				cons.put("messNum", messNum);//总消息数
				
				map.put("data", cons);
				map.put("msg", "暂无咨询");
				map.put("code", 1);
				jsons = JSONObject.fromObject(map);// 将java对象转换为json对象
				msg = jsons.toString();
			}
		} catch (Exception e) {
			e.printStackTrace();
			map.put("msg", "获取详细信息失败"+e.getMessage().replaceAll("",""));
			map.put("code", 2);
			jsons = JSONObject.fromObject(map);
		}
		return msg;
	}
	
	
	/**
	 * APP查询单个咨询详细
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/getConsleApp", method = RequestMethod.POST, produces = "text/json;charset=UTF-8")
	@ResponseBody
	public String getConsleApp(HttpServletRequest request, Model model) {
		Map<String, Object> map=new HashMap<String, Object>();
		JSONObject jsons =null;
		
		String msg=null;
		JSONObject jsonObject = null;
		String userid =null;//用户id
		String id="";//消息id
		int readornot=0;//消息状态(0：已读)
		String json = request.getParameter("json");
		jsonObject = JSONObject.fromObject(json);
		try{
			userid =jsonObject.getString("userid");
			id =jsonObject.getString("id");
			readornot =jsonObject.getInt("readornot");
		}catch(Exception e){
			map.put("msg", "参数有误"+e.getMessage().replaceAll("",""));
			map.put("code", 9002);
			jsons = JSONObject.fromObject(map);
            return msg;
		}
		try {
			Consultation recons = new Consultation();
			recons.setId(id);
			recons.setReadornot(readornot);
			consultationservice.updatereadtype(recons);
			
			Consultation cons = consultationservice.selConsId(id);//根据登录查看单条详细
			ConsultingAppsingle consapp=new ConsultingAppsingle();
			BeanUtils.copyProperties(consapp, cons);
			map.put("data", consapp);
			map.put("code", 1);
			jsons = JSONObject.fromObject(map);// 将java对象转换为json对象
			msg = jsons.toString();
		} catch (Exception e) {
			e.printStackTrace();
			map.put("msg", "获取详细信息失败"+e.getMessage().replaceAll("",""));
			map.put("code", 2);
			jsons = JSONObject.fromObject(map);
			return msg;
		}
		return msg;
	}
	
	/**********/
	/**
	 * APP查看评论
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/getcommentlistApp", method = RequestMethod.POST, produces = "text/json;charset=UTF-8")
	@ResponseBody
	public String getcommentlistApp(HttpServletRequest request, Model model) {
		Map<String, Object> map=new HashMap<String, Object>();
		JSONObject jsons =null;
		String msg=null;
		JSONObject jsonObject = null;
		/**入参***/
		String userid =null;//用户id
		String currentPageStr = null;//页码 
		String consid = "";//咨询对应数据id
		/******/
		int pageSize = 10;
		String json = request.getParameter("json");
		jsonObject = JSONObject.fromObject(json);
		try{
			userid =jsonObject.getString("userid");
			currentPageStr =jsonObject.getString("currentPage");
			consid =jsonObject.getString("consultation_id");
		}catch(Exception e){
			map.put("msg", "参数有误"+e.getMessage().replaceAll("",""));
			map.put("code", 9002);
			jsons = JSONObject.fromObject(map);
            return jsons.toString();
		}

		// 获取当前页数
		int currentPage = 1;
		try {
			if(currentPageStr!=null && currentPageStr!=""){
				currentPage = Integer.parseInt(currentPageStr);
			}
		} catch (Exception e) {
		}
		currentPage = currentPage <= 0 ? 1 : currentPage;
		
		try {
			Map<String, Object> cons = consultationservice.selcommentId(consid, pageSize, currentPage);
			int commNum = ((List)cons.get("list")).size(); //
			if(commNum > 0){
				cons.put("pageSize", pageSize);
				cons.put("currentPage", currentPage);
				cons.put("commNum", commNum);//总消息数
				
				map.put("data", cons);
				map.put("code", 1);
				jsons = JSONObject.fromObject(map);// 将java对象转换为json对象
				msg = jsons.toString();
			} else {
				cons.put("pageSize", pageSize);
				cons.put("currentPage", currentPage);
				cons.put("commNum", commNum);//总消息数
				
				map.put("data", cons);
				map.put("msg", "暂无评论");
				map.put("code", 1);
				jsons = JSONObject.fromObject(map);// 将java对象转换为json对象
				msg = jsons.toString();
			}
		} catch (Exception e) {
			e.printStackTrace();
			map.put("msg", "获取评论信息失败"+e.getMessage().replaceAll("",""));
			map.put("code", 2);
			jsons = JSONObject.fromObject(map);
		}
		return msg;
	}
	
	/**
	 * 增加评论
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/AddcommentApp", method = RequestMethod.POST, produces = "text/json;charset=UTF-8")
	@ResponseBody
	public String AddcommentApp(HttpServletRequest request, Model model) {
		Map<String, Object> map=new HashMap<String, Object>();
		JSONObject jsons =null;
		String msg=null;
		JSONObject jsonObject = null;
		/***入参***/
		int consid;//作品id
		String content="";//评论内容
		int userid ;//评论用户id
		/********/
		String json = request.getParameter("json");
		try {
			json=java.net.URLDecoder.decode(json,"UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		jsonObject = JSONObject.fromObject(json);
		
		try{
			consid =jsonObject.getInt("consultation_id");
			content =jsonObject.getString("content");
			userid =jsonObject.getInt("userid");
		}catch(Exception e){
			map.put("msg", "参数有误"+e.getMessage().replaceAll("",""));
			map.put("code", 9002);
			jsons = JSONObject.fromObject(map);
            return msg;
		}
		
		try {
			long date = new Date().getTime();  
			System.out.println(date);
			Comment comm = new Comment();
			comm.setConsultation_id(consid);
			comm.setArticletype_type(1);
			//String str=new String(content.getBytes("ISO-8859-1"),"UTF-8");
			comm.setContent(content);
			comm.setFrom_uid(userid);
			comm.setComment_date(date);
			consultationservice.insertComment(comm);
			
			Comment comment = consultationservice.CommentById(comm.getId(), consid);
			
			CommentAppBean commapp=new CommentAppBean();
			BeanUtils.copyProperties(commapp, comment);
			map.put("data", commapp);
			map.put("code", 1);
			jsons = JSONObject.fromObject(map);// 将java对象转换为json对象
			msg = jsons.toString();
		} catch (Exception e) {
			e.printStackTrace();
			map.put("msg", "获取评论失败"+e.getMessage().replaceAll("",""));
			map.put("code", 2);
			jsons = JSONObject.fromObject(map);
			return msg;
		}
		return msg;
	}
}
